﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Serialization;

namespace ResourceViewerExtension.Common
{
    public static class UserSettingsManager
    {
        private const string FILE_NAME = "UserSettings";
        public static SerializableDictionary<string, string> Settings { get; private set; }

        public static void SaveSettings(Dictionary<string, string> settings)
        {
            SaveToDisk(new SerializableDictionary<string, string>(settings));
        }

        public static void LoadSettings()
        {
            LoadFromDisk();
        }

        private static void SaveToDisk(SerializableDictionary<string, string> stt)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
                {
                    IsolatedStorageFileStream stream;
                    if (store.GetFileNames(FILE_NAME).Length > 0)
                    {
                        stream = new IsolatedStorageFileStream(FILE_NAME, FileMode.Truncate, FileAccess.Write, store);
                    }
                    else
                    {
                        stream = new IsolatedStorageFileStream(FILE_NAME, FileMode.Create, FileAccess.Write, store);
                    }
                    using (stream)
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, string>));
                        serializer.Serialize(stream, stt);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void LoadFromDisk()
        {
            SerializableDictionary<string, string> list = null;
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
                {
                    if (store.GetFileNames(FILE_NAME).Length > 0)
                    {
                        using (IsolatedStorageFileStream stream = new
                          IsolatedStorageFileStream(FILE_NAME, FileMode.Open, FileAccess.Read, store))
                        {
                            XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, string>));
                            list = serializer.Deserialize(stream) as SerializableDictionary<string, string>;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (list == null) list = new SerializableDictionary<string, string>();
            Settings = list;
        }
    }
}
